<template>
  <div v-if="!webModel && tileFlag" class="menu-grid">
    <div class="select-block">
      <el-select v-model="categoryFilter" clearable>
        <el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
    </div>
    <el-row :gutter="20">
      <el-col v-for="item in displayCategory" :key="item.id" :span="6" @click.native="selectCategory(item)">
        <div class="menu-grid-content">{{ item.name }}</div>
      </el-col>
    </el-row>
  </div>
  <el-container v-else class="el-container-h">
    <el-header v-if="!webModel" class="header_back">
      <el-button type="text" @click="tileFlag = true">
        <i class="el-icon-arrow-left el-icon--left">返回</i>
      </el-button>
    </el-header>
    <PanelGroup
      class="aside-panel"
      :data="category"
      :list-model="true"
      :tree-model="true"
      :tile-model="false"
      @click="selectCategory"
    />
    <el-main>
      <div v-for="(tab,key) in mainTable" :key="key" class="table-block">
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <h3 class="table-title">{{ tab.name }}</h3>
          </el-col>
          <el-col :span="12" align="right">
            <el-input v-if="tab.filterFlag" v-model="ciFilter" size="mini" :placeholder="CONSTANT.placeholder" class="iteminput" />
            <el-button v-if="tab.addFlag" type="primary" plain size="mini" icon="el-icon-plus" :disabled="!tab.addData" @click="edit(tab.tag,tab.addData,tab.addAction,`${CONSTANT.add} - ${tab.name}`,tab.clickAction)">{{ CONSTANT.add }}</el-button>
          </el-col>
        </el-row>
        <el-table border style="width: 100%" max-height="500" :data="tab.data" @row-click="actionRouter($event,tab.clickAction)">
          <el-table-column
            v-for="(item, index) in tab.column"
            :key="index"
            :label="item.name"
            :min-width="item.minwidth"
          >
            <template slot-scope="scope">
              <span>{{ scope.row[index] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="tab.modifyFlag" :label="CONSTANT.operate" width="180">
            <template slot-scope="scope">
              <el-button size="mini" :disabled="scope.row.self_flag===false" @click.stop="edit(tab.tag,scope.row,tab.modifyAction,`${CONSTANT.modify} - ${tab.name}`)">{{ CONSTANT.modify }}</el-button>
              <el-button size="mini" type="danger" :disabled="scope.row.self_flag===false" @click.stop="remove(scope.row,tab.deleteAction)">{{ CONSTANT.delete }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <!-- 添加/编辑 弹窗 -->
    <el-dialog v-if="modelFlag" :title="modelTitle" :visible="modelFlag" append-to-body @close="modelFlag=!modelFlag">
      <edit-model :data="modelData" @submit="submit" @cancel="modelFlag=!modelFlag" />
    </el-dialog>
  </el-container>
</template>
<script>
import { mapState, mapActions } from 'vuex'
const CONSTANT = {
  placeholder: '请输入关键字',
  deleteConfirm: '您确定删除吗?',
  operate: '操作',
  add: '添加',
  delete: '删除',
  modify: '编辑',
  ciTitle: '配置项(ci)基本信息',
  ciInfoTitle: '配置项(ci)属性',
  infoTitle: '配置项(ci)可配置属性',
  infosetTitle: '配置项(ci)可配置属性约束值',
  ciRelationTitle: '配置项(ci)关联关系',
  categoryRelationTitle: '配置项(ci)可配置关联关系',
  ciColumn: [
    'uid',
    'flag',
    'category_uid',
    'category_name',
    'id',
    'name',
    'parent_uid',
    'parent_name',
    'previous_uid',
    'previous_name'
  ],
  ciInfoColumn: [
    'uid',
    'flag',
    'category_uid',
    'category_name',
    'item_uid',
    'item_name',
    'info_uid',
    'info_name',
    'infoset_uid',
    'infoset_name',
    'value'
  ],
  ciRelationColumn: [
    'uid',
    'flag',
    'relation_uid',
    'relation_name',
    'target_uid',
    'target_name',
    'origin_uid',
    'origin_name',
    'value'
  ],
  infoColumn: [
    'uid',
    'flag',
    'category_uid',
    'category_name',
    'id',
    'name'
  ],
  infosetColumn: [
    'uid',
    'flag',
    'category_uid',
    'category_name',
    'id',
    'name',
    'info_uid',
    'info_name',
    'value'
  ],
  relationColumn: [
    'uid',
    'flag',
    'id',
    'name',
    'target_uid',
    'target_name',
    'origin_uid',
    'origin_name'
  ]
}
export default {
  name: 'SystemConfig',
  components: {
    editModel: () => import('@components/EditModel.vue'),
    PanelGroup: () => import('@components/PanelGroup.vue')
  },
  data() {
    return {
      CONSTANT,
      tileFlag: true, // 磁贴显示标识
      modelFlag: false, // 编辑框--显示隐藏
      modelTitle: null, // 编辑框--标题
      modelData: null, // 编辑框--内容
      modelFunction: null, // 编辑框--提交方法
      modelCallback: null, // 编辑框--回调
      categoryFilter: null, // 类型搜索条件(树,磁贴)
      ciFilter: null, // 实例搜索条件
      selectedCategory: null, // 被选择的类型(树节点,磁贴)
      selectedCi: null, // 被选择的实例
      selectedInfo: null, // 被选择的属性
      selectedRelation: null, // 被选择的关联关系
      rowClickActin: null, // 表格行点击事件
      ci: null, // 实例数据
      ciInfo: null, // 属性数据
      ciRelation: null // 关联数据
    }
  },

  computed: {
    ...mapState({
      service: state => state.service,
      webModel: state => state.authentication.webModel,
      treeTemplate: state => state.component.treeTemplate
    }),
    ...mapState('systemProfile', {
      display: state => state.display,
      category: state => state.category,
      info: state => state.info.filter(item => item.uid),
      infoset: state => state.infoset.filter(item => item.uid),
      relation: state => state.relation
    }),
    mainTable() {
      return {
        ci: {
          name: this.CONSTANT.ciTitle,
          addAction: this.isCategory ? this.service.createCategory : this.service.addCi,
          deleteAction: this.isCategory ? this.service.dropCategory : this.service.deleteCi,
          modifyAction: this.isCategory ? this.service.alterCategory : this.service.updateCi,
          clickAction: this.selectCi,
          tag: this.CONSTANT.ciColumn,
          filterFlag: true,
          modifyFlag: true,
          addFlag: true,
          addData: this.selectedCategory ? { category_uid: this.selectedCategory.uid } : null,
          data: this.displayCi,
          column: this.CONSTANT.ciColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        },
        ciInfo: {
          name: this.CONSTANT.ciInfoTitle,
          addAction: this.service.addCiInfo,
          deleteAction: this.service.deleteCi,
          modifyAction: this.service.updateCiInfo,
          clickAction: this.selectInfo,
          tag: this.CONSTANT.ciInfoColumn,
          filterFlag: false,
          modifyFlag: true,
          addFlag: true,
          addData: this.selectedCi ? {
            category_uid: this.selectedCategory.uid,
            item_uid: this.selectedCi.uid
          } : null,
          data: this.ciInfo,
          column: this.CONSTANT.ciInfoColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        },
        info: {
          name: this.CONSTANT.infoTitle,
          clickAction: this.selectInfo,
          tag: this.CONSTANT.infoColumn,
          filterFlag: false,
          modifyFlag: false,
          addFlag: false,
          data: this.info.filter(item => this.selectedCategory && this.selectedCategory.uid === item.category_uid),
          column: this.CONSTANT.infoColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        },
        infoset: {
          name: this.CONSTANT.infosetTitle,
          addAction: this.service.addInfoset,
          deleteAction: this.service.deleteCi,
          modifyAction: this.service.updateInfoset,
          tag: this.CONSTANT.infosetColumn,
          filterFlag: false,
          modifyFlag: true,
          addFlag: true,
          addData: this.selectedInfo ? { info_uid: this.selectedInfo.uid } : null,
          data: this.infoset.filter(item => this.selectedInfo && this.selectedInfo.uid === item.info_uid),
          column: this.CONSTANT.infosetColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        },
        relation: {
          name: this.CONSTANT.categoryRelationTitle,
          addAction: this.service.createRelation,
          deleteAction: this.service.dropRelation,
          modifyAction: this.service.updateRelation,
          clickAction: this.selectRelation,
          tag: this.CONSTANT.relationColumn,
          filterFlag: false,
          modifyFlag: true,
          addFlag: true,
          addData: true,
          data: this.selectedCategory ? this.relation.filter(item =>
            item.origin_uid === this.selectedCategory.uid ||
            item.target_uid === this.selectedCategory.uid
          ) : null,
          column: this.CONSTANT.relationColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        },
        ciRelation: {
          name: this.CONSTANT.ciRelationTitle,
          addAction: this.service.addCiRelation,
          deleteAction: this.service.deleteCi,
          modifyAction: this.service.updateCiRelation,
          tag: this.CONSTANT.ciRelationColumn,
          filterFlag: false,
          modifyFlag: true,
          addFlag: true,
          addData: this.selectedRelation ? { relation_uid: this.selectedRelation.relation_uid } : null,
          data: this.ciRelation,
          column: this.CONSTANT.ciRelationColumn.reduce((result, key) => (
            this.display[key] && this.display[key].show
              ? { ...result, [key]: this.display[key] }
              : result), {}
          )
        }
      }
    },
    // 当前选择的对象是否为类型
    isCategory() {
      return this.selectedCategory ? this.selectedCategory.uid === this.selectedCategory.category_uid : null
    },
    // 类型数据
    displayCategory() {
      if (this.categoryFilter && this.categoryFilter.trim()) {
        return this.category.filter(item =>
          item.id.toLowerCase().indexOf(this.categoryFilter.trim().toLowerCase()) !== -1 ||
          item.name.toLowerCase().indexOf(this.categoryFilter.trim().toLowerCase()) !== -1
        )
      } else {
        return this.category
      }
    },
    // 实例数据
    displayCi() {
      if (this.ci && this.ciFilter && this.ciFilter.trim()) {
        return this.ci.filter(item =>
          item.id.toLowerCase().indexOf(this.ciFilter.trim().toLowerCase()) !== -1 ||
          item.name.toLowerCase().indexOf(this.ciFilter.trim().toLowerCase()) !== -1 ||
          (item.parent_name && item.parent_name.toLowerCase().indexOf(this.ciFilter.trim().toLowerCase()) !== -1) ||
          (item.previous_name && item.previous_name.toLowerCase().indexOf(this.ciFilter.trim().toLowerCase()) !== -1)
        )
      } else {
        return this.ci
      }
    }
  },
  async created() {
    await this.initData()
  },
  methods: {
    ...mapActions([
      'init'
    ]),
    // 初始化
    async initData() {
      await this.init()
    },
    // 获取实例数据
    async getCi() {
      if (this.selectedCategory) {
        const result = await this.service.getCi({ category_uid: this.selectedCategory.uid })
        if (!result.flag) {
          this.$message.error(`${result.id} : ${result.name}`)
        } else if (result.data) {
          this.ci = result.data
        }
      }
    },
    // 获取实例属性
    async getInfo() {
      if (this.selectedCi) {
        const result = await this.service.getCiInfo(this.selectedCi)
        if (!result.flag) {
          this.$message.error(`${result.id} : ${result.name}`)
        } else if (result.data) {
          this.ciInfo = result.data.filter(item => item.uid)
        }
      }
    },
    // 获取实例关联关系
    async getRelation() {
      if (this.selectedCi) {
        const result = await this.service.getCiRelation(this.selectedCi)
        if (!result.flag) {
          this.$message.error(`${result.id} : ${result.name}`)
        } else if (result.data) {
          this.ciRelation = result.data.filter(item => item.uid)
        }
      }
    },
    // 树节点,磁贴点击
    async selectCategory(data) {
      this.tileFlag = false
      this.ciFilter = null
      if (this.selectedCategory !== data) {
        this.selectedCategory = data
        this.selectedRelation = null
        this.selectedCi = null
        this.selectedInfo = null
        this.ci = null
        this.ciInfo = null
        this.ciRelation = null
        await this.getCi()
        await this.getInfo()
        await this.getRelation()
      }
    },
    // 实例列表点击
    async selectCi(data) {
      if (this.selectedCi !== data) {
        this.selectedCi = data
        this.selectedInfo = null
        this.ciInfo = null
        this.ciRelation = null
        this.getInfo()
        this.getRelation()
      }
    },
    // 实例列表点击
    selectInfo(data) {
      this.selectedInfo = data
    },
    // 关联关系点击
    selectRelation(data) {
      this.selectedRelation = data
    },
    // 添加,编辑配置藉由
    edit(tag, data, action, title) {
      this.modelFlag = !this.modelFlag
      this.modelTitle = title
      this.modelFunction = action
      this.modelData = tag.reduce((result, key) => ({ ...result, [key]: data[key] }), {})
    },
    // 提交数据
    async submit(data) {
      const result = await this.modelFunction(data)
      if (!result.flag) {
        this.$message.error(`${result.id} : ${result.name}`)
      } else {
        this.modelFlag = !this.modelFlag
        await this.initData()
        // if (this.modelCallback && result.data && result.data.length > 0) {
        //   this.modelCallback(result.data[0]);
        // }
      }
    },
    // 删除数据
    async removeData(data, modelFunction = this.service.deleteCi) {
      const result = await modelFunction(data)
      if (!result.flag) {
        this.$message.error(`${result.id} : ${result.name}`)
      } else if (result.data) {
        await this.initData()
      }
    },
    remove(data, action = this.service.deleteCi) {
      this.$confirm(this.CONSTANT.deleteConfirm)
        .then(_ => {
          this.removeData(data, action)
        })
        .catch(() => {})
    },
    actionRouter(data, action) {
      if (action) {
        this.rowClickActin = action
        this.rowClickActin(data)
      }
    },
    changeFilter(data) {
      this.categoryFilter = data
    },
    filterSearch(string, cb) {
      // 调用 callback 返回建议列表的数据
      cb(this.displayCategory)
    }
  }

}
</script>
<style>
.explorer-content {
  position: relative;
}
</style>
<style scoped>
.el-container-h {
    width: 100%;
    height: 100%;
    position: absolute;
}
.app-frame {
    height: 100vh;
}
.select-block {
  margin-bottom: 2rem;
  text-align: right;
}
.table-block {
  border: 1px solid #ebebeb;
  border-radius: 3px;
  padding: 2rem;
  margin-bottom: 2rem;
  min-width: 50rem;
}
.aside-panel{
  width: 13rem;
  padding:1rem;
  background-color: rgb(238, 241, 246);
}
.el-main .table-block:last-child {
  margin-bottom: 0;
}
.el-main .table-block .el-select {
  margin-right: 1rem;
}
.el-input--mini .el-input__inner {
    height: 29px;
    line-height: 29px;
}
.iteminput {
    width: auto;
    margin-right: 1rem;
}
.table-block table tbody tr {
  cursor: pointer;
}
.table-title {
  padding-bottom: 1rem;
}
.header_back {
    background-color: rgb(238, 241, 246);
    border-bottom: 1px solid #ccc;
    line-height: 3rem;
    height: 3rem !important;
}
.header_back button {
    outline: none !important;
    padding-top: 0;
    padding-bottom: 0;
}
.menu-grid {
    padding: 1rem;
    padding-bottom: 0;
    overflow: auto;
}
.menu-grid-content {
    height: 20rem;
    background: #d3dce6;
    margin-bottom: 1rem;
    cursor: pointer;
    text-align: center;
}
.dialog /deep/ .dialog-footer {
  text-align: right;
  padding-top: 3rem;
}
</style>
